//
//  HELHomeVC.m
//  NursingAssociation
//
//  Created by wsj2015 on 2017/2/13.
//  Copyright © 2017年 wsj2015. All rights reserved.
//

#import "HELHomeVC.h"
#import "CSStickyHeaderFlowLayout.h"
#import "HELNavigationController.h"
#import "UINavigationController+WXSTransition.h"
#import "BTLoginVC.h"
#import "UIView+WZLBadge.h"
#import "HELCatogeryCell.h"
#import "HELGrowHeader.h"
#import "BTSearchBar.h"
#import "HELHomeCell.h"
#import "HELHomeCollectSectiionHeader.h"
#import "HELHomeFooter.h"
#import "HELCatorgyModel.h"

#import "HELRankingListVC.h"
#import "HELSearchHistoryVC.h"
#import "HELCourseListByCatogryVC.h"
#import "HELMessageListVC.h"
#import "NHCourseDetailVC.h"
#import "BTBaseWebVC.h"
#import "GzwTableViewLoading.h"
#import "HELCatogryModel.h"
#import "HELCourseListModel.h"
#import "NHCourseDetailVC.h"
#import "MessageServicer.h"
//#import "IAPShare.h"
@interface HELHomeVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,UISearchBarDelegate,KCBannerViewDataSource,KCBannerViewDelegate>

@property (nonatomic,  strong) UICollectionView *collectView;


@property (nonatomic,  strong) BTSearchBar *searchBar;

@property (nonatomic,  strong) NSMutableArray *catorgryArray;


@property (nonatomic,  assign) NSInteger freshStatus;
@property (nonatomic,  strong) UIButton *messageBtn;

@property (nonatomic,  strong) NSMutableArray *bannerArr;


@end

@implementation HELHomeVC



- (instancetype)init
{
    self = [super init];
    if (self) {
//      self.isShowNetwork = YES;
    }
    return self;
}

- (NSMutableArray *)catorgryArray{
    if (!_catorgryArray) {
        _catorgryArray = [NSMutableArray array];
    }
    return _catorgryArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    //监听登陆和退出登陆消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sucessLogin) name:LoginSuccessNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logout) name:LogoutNotification object:nil];
     [self addObserver:self forKeyPath:@"freshStatus" options:NSKeyValueObservingOptionNew context:nil];
    if (![HELAppManager userInfo]) {
        BTLoginVC *vc =[BTLoginVC new];
        HELNavigationController *nav =[[HELNavigationController alloc] initWithRootViewController:vc];
        [self wxs_presentViewController:nav animationType:WXSTransitionAnimationTypeInsideThenPush completion:nil];
        return;
    }else{
        [self sucessLogin];
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    if ([keyPath isEqualToString:@"freshStatus"]) {
        NSInteger freshstatus = [change[@"new"] integerValue];
        if (freshstatus == 0) {
            [self.collectView.header endRefreshing];
            [self.collectView reloadData];
        }
    }
}

- (void)logout{

}

- (void)sucessLogin{
    [self.collectView.header beginRefreshing];
 
    
}

- (BTSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [BTSearchBar searchBarWithDelegate:self];
       
    }
    return _searchBar;
}
- (void)configUI{
    [self.collectView registerNib:[UINib nibWithNibName:@"HELCatogeryCell" bundle:nil] forCellWithReuseIdentifier:@"HELCatogeryCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCell" bundle:nil] forCellWithReuseIdentifier:@"HELHomeCell"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeCollectSectiionHeader" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HELHomeCollectSectiionHeader"];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELHomeFooter" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"HELHomeFooter"];
    
    [self.view addSubview:self.collectView];
    [self.collectView registerNib:[UINib nibWithNibName:@"HELGrowHeader" bundle:nil]
       forSupplementaryViewOfKind:CSStickyHeaderParallaxHeader
              withReuseIdentifier:@"HELGrowHeader"];
    
    //消息按钮
    UIButton *btn =[UIButton buttonWithType:UIButtonTypeSystem];
    btn.frame = CGRectMake(0, 0, 33, 33);
    [btn setImage:[UIImage imageNamed:@"消息"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(messageNot) forControlEvents:UIControlEventTouchUpInside];
    self.messageBtn = btn;
    btn.badgeBgColor = [UIColor whiteColor];
    [btn showBadgeWithStyle:WBadgeStyleRedDot value:1 animationType:WBadgeAnimTypeBreathe];
 
    btn.badgeCenterOffset = CGPointMake(-8, 10);
    UIBarButtonItem *right1 =[[UIBarButtonItem alloc] initWithCustomView:btn];
    
    self.navigationItem.titleView = self.searchBar;
    UIBarButtonItem *fixItem =[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixItem.width = -100;
    
    UIBarButtonItem *menuBtn =[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"扫一扫 copy"] style:UIBarButtonItemStyleDone target:self action:@selector(menuAction)];
    
    self.navigationItem.rightBarButtonItems =@[right1,fixItem,menuBtn];
    defineWeakSelf;

    
    [self.collectView wsj_HeaderRefreshBlock:^{
        [weakSelf requestCatogryList];
        [weakSelf getBannerList];
        [weakSelf reqestCourseList];
    }];

}

- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
   
    weakSelf_define;
    [[MessageServicer shareServicer] requestPersonInfoWithSucess:^(NSInteger unread) {
      
          unread >0?[weakSelf.messageBtn resumeBadge]:[weakSelf.messageBtn clearBadge];
      
    }];
    
}
- (UICollectionView *)collectView{
    if (!_collectView) {
        
        CSStickyHeaderFlowLayout *layout =[[CSStickyHeaderFlowLayout alloc]init];
        
        
        CGFloat f = kScreenFactor;
        //        if ([layout isKindOfClass:[CSStickyHeaderFlowLayout class]]) {
        layout.parallaxHeaderReferenceSize = CGSizeMake(self.view.frame.size.width, 162 * f);
        layout.parallaxHeaderMinimumReferenceSize = CGSizeMake(kScreenWidth, 162 * f);
        layout.itemSize = CGSizeMake(self.view.frame.size.width, layout.itemSize.height);
        // If we want to disable the sticky header effect
        layout.disableStickyHeaders = NO;
        //        }
 
        CGFloat space = 8;
        
        layout.sectionInset =UIEdgeInsetsMake(4, space, 2, space );
        layout.minimumInteritemSpacing = 4;
        layout.minimumLineSpacing = 6;
        CGRect frame =CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64 -49);
        _collectView =[[UICollectionView alloc]initWithFrame:frame collectionViewLayout:layout];
        _collectView.delegate = self;
        _collectView.dataSource = self;
        _collectView.showsVerticalScrollIndicator = NO;
        _collectView.alwaysBounceVertical =YES;
        _collectView.backgroundColor = kAppBg;
        if ([_collectView respondsToSelector:@selector(setPrefetchingEnabled:)]) {
            _collectView.prefetchingEnabled = NO;
        }
        //
        
        
    }
    return _collectView;
    
}




- (void)menuAction{
  
//    if(![IAPShare sharedHelper].iap) {
//        NSSet* dataSet = [[NSSet alloc] initWithObjects:@"NursingAssociation00001", nil];
//        
//        [IAPShare sharedHelper].iap = [[IAPHelper alloc] initWithProductIdentifiers:dataSet];
//    }
//    //设置是否为沙盒路径
//    [IAPShare sharedHelper].iap.production = YES;
//    //进行内购以及相关回调,请注意,这一步的时候一定要退出真机的apple账号!不然没法登陆测试账号
//    [[IAPShare sharedHelper].iap requestProductsWithCompletion:^(SKProductsRequest* request,SKProductsResponse* response)
//     {
//         if(response > 0 ) {
//             SKProduct* product =[[IAPShare sharedHelper].iap.products firstObject];
//             NSLog(@"商品信息 -> %@",product.mj_keyValues);
//             //             product.mj_JSONString
////             self.iapLabel.text = [NSString stringWithFormat:@"商品信息 -> \n%@",product.mj_JSONString];
//             [[IAPShare sharedHelper].iap buyProduct:product
//                                        onCompletion:^(SKPaymentTransaction* trans){
//                                            
//                                            if(trans.error)
//                                            {
//                                                NSLog(@"此处错误");
//                                                NSLog(@"Fail %@",[trans.error localizedDescription]);
////                                                self.iapLabel.text = [trans.error localizedDescription];
//                                                
//                                            }
//                                            else if(trans.transactionState == SKPaymentTransactionStatePurchased) {
//                                                //这里输入公共秘钥
//                                                [[IAPShare sharedHelper].iap checkReceipt:trans.transactionReceipt AndSharedSecret:@"912bb173d02c46dfabfea25f63f493b6" onCompletion:^(NSString *response, NSError *error) {
//                                                    
//                                                    //Convert JSON String to NSDictionary
//                                                    NSDictionary* rec = [IAPShare toJSON:response];
//                                                    
//                                                    if([rec[@"status"] integerValue]==0)
//                                                    {
//                                                        NSLog(@"购买成功");
////                                                        self.iapLabel.text = @"购买成功";
//                                                        [[IAPShare sharedHelper].iap provideContentWithTransaction:trans];
//                                                        NSLog(@"SUCCESS %@",response);
//                                                        NSLog(@"Pruchases %@",[IAPShare sharedHelper].iap.purchasedProducts);
//                                                        
////                                                        self.iapLabel.text = [NSString stringWithFormat:@"SUCCESS %@ \nPruchases %@",response,[IAPShare sharedHelper].iap.purchasedProducts];
//                                                        
//                                                    }
//                                                    else {
//                                                        NSLog(@"Fail");
////                                                        self.iapLabel.text = @"Fail";
//                                                    }
//                                                }];
//                                            }
//                                            else if(trans.transactionState == SKPaymentTransactionStateFailed) {
//                                                NSLog(@"Fail");
////                                                self.iapLabel.text = @"Fail";
//                                            }
//                                        }];//end of buy product
//         }
//     }];
//    
    
    
    
}

#pragma mark -请求banner数据
- (void)getBannerList{
    
    
    weakSelf_define;
    self.freshStatus ++;
    [[HELNetworkManager sharedMg] GET:kBannerUrl parameters:nil success:^(id responseObject) {
         weakSelf.freshStatus--;
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            weakSelf.bannerArr = [[BTBannerModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]] copy];
           
            [weakSelf.collectView reloadData];
        }
    } failure:^(NSString *err) {
        weakSelf.freshStatus--;
    }];
    
}

#pragma mark -请求首页课程列表
- (void)reqestCourseList{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    params[@"page"] = @(1);
    params[@"rows"] = @(6);
   
    if (!self.dataArray.count) {
        [self wsj_showLodingGif];
    }
    weakSelf_define;
    weakSelf.freshStatus ++;
    [[HELNetworkManager sharedMg] POST:helCourseSearchUrl parameters:params success:^(id responseObject) {
        [self wsj_hideLodingGif];
        weakSelf.freshStatus --;
      
      
        if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
            
           
            [weakSelf.dataArray removeAllObjects];
           
            [weakSelf.dataArray addObjectsFromArray:[HELCourseListModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"][@"data"]]];
           
            [weakSelf.collectView reloadData];
            
        }
        
        
    } failure:^(NSString *err) {
        [self wsj_hideLodingGif];
        [weakSelf.collectView.header endRefreshing];
        weakSelf.freshStatus --;
    }];
    
    
    

}

#pragma mark -请求课程类别
- (void)requestCatogryList{
    
    weakSelf_define;
    self.freshStatus ++;
    [[HELNetworkManager sharedMg] GET:kCourseCatogry parameters:nil success:^(NSDictionary * responseObject) {
        [weakSelf.catorgryArray removeAllObjects];
        weakSelf.freshStatus --;
        NSArray *array = [HELCatogryModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
        if (array.count>=7) {
            for (int i = 0;i<7;i++) {
                [weakSelf.catorgryArray addObject:array[i]];
            }
        }else{
          [weakSelf.catorgryArray addObjectsFromArray:array];
        }
       
        
        
        [weakSelf.collectView reloadData];
    } failure:^(NSString *err) {
        weakSelf.freshStatus --;
        
    }];
}
#pragma mark 点击进入消息通知
- (void)messageNot{
    
    HELMessageListVC *vc =[HELMessageListVC new];
    [self.navigationController pushViewController:vc animated:YES];

}
#pragma mark -KCBannerViewDatasource
- (BTBannerModel *)bannerView:(KCBannerView *)bannerView bannerForItemAtIndex:(NSInteger)index
{
    return self.bannerArr[index];
}

- (NSInteger)numberOfBannersInBannerView:(KCBannerView *)bannerView
{
    return self.bannerArr.count;
}
#pragma mark -轮播被点击
- (void)bannerView:(KCBannerView *)bannerView didSelectBannerAtIndex:(NSInteger)index{
 
    
    BTBannerModel *bannerModel =  self.bannerArr[index];
    if ([bannerModel.bannerType  integerValue] == 1) {
        //课程
       
        NHCourseDetailVC *vc =[NHCourseDetailVC new];
        vc.courseId =  [bannerModel.bannerTarget integerValue];
        vc.title  =@"资讯详情";
        [self.navigationController pushViewController:vc animated:YES];
       
    }else{
       //资讯
        BTBaseWebVC *webVC = [[BTBaseWebVC alloc] init];
        NSString *url ;
        url = [NSString stringWithFormat:@"%@/%@/%@",[HELNetworkManager sharedMg].bathURL,kCousultDetail,bannerModel.bannerTarget];
        webVC.theUrl = [NSURL URLWithString:url];
        //        webVC.title = model.title;
        [self.navigationController pushViewController:webVC animated:YES];
    }
    
}


- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0 ) {
        return CGSizeMake((kScreenWidth -26 *2)/4, 92);
    }else{
        
        //适配屏幕
        CGFloat w = (kScreenWidth -24)/2;
        CGFloat h =160;
        CGFloat f = kScreenFactor;
        
        
        return CGSizeMake(w, h * f);
    }
    
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    if (section ==0) {
        return  CGSizeZero;
    }
    if ([self.dataArray count]==0) {
        return CGSizeMake(0, 0);
    }
    if (self.catorgryArray.count == 0) {
        return CGSizeMake(0, 0);
    }
    
    return CGSizeMake(kScreenWidth, 33);
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (self.catorgryArray.count == 0) {
        return CGSizeMake(0, 0);
    }
    return CGSizeMake(kScreenWidth, 18);
}

#pragma mark UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (section == 0) {
        if (!self.catorgryArray.count) {
            return 0;
        }
        return self.catorgryArray.count + 1;
    }
    return [self.dataArray count] ;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    weakSelf_define;
    //    NSDictionary *obj = self.dataArray[indexPath.section];
    if (indexPath.section ==0) {
        HELCatogeryCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"HELCatogeryCell"
                                                                          forIndexPath:indexPath];
        if (indexPath.row<self.catorgryArray.count) {
            HELCatogryModel *model =self.catorgryArray[indexPath.row];
            cell.model = model;
        }else{
            cell.icon.image = [UIImage imageNamed:@"更多_icon"];
            cell.nameL.text = @"更多";
        }
//        cell.clickBlock = ^(NSInteger index){
////            [weakSelf goIntoCourseVC:index indexPath:indexPath];
//        };
        return cell;
    }
    
    HELHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HELHomeCell"
                                                                  forIndexPath:indexPath];
    
        HELCourseListModel *model =self.dataArray[indexPath.row];
        cell.model = model;
  
    
    
    
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        
        //        NSDictionary *obj = self.dataArray[indexPath.section];
        
        HELHomeCollectSectiionHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                                withReuseIdentifier:@"HELHomeCollectSectiionHeader"
                                                                                       forIndexPath:indexPath];
        // HELDepartmentModel *model =self.dataArray[indexPath.section-1];
        
//        cell.titleL.text =@[@"院内课程",@"公开课程"][indexPath.section-1];
        
        defineWeakSelf;
        cell.getMoreBlock = ^(){
//            [weakSelf goIntoCourseVC:-1 indexPath:indexPath];
            [weakSelf.navigationController pushViewController: [HELRankingListVC new] animated:YES];
            
        };
        
        return cell;
    }else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
        
        HELHomeFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"HELHomeFooter" forIndexPath:indexPath];
        footer.backgroundColor = kTableView_bg;
        
        return  footer;
        
    }else if ([kind isEqualToString:CSStickyHeaderParallaxHeader]) {
        HELGrowHeader *cell = [collectionView dequeueReusableSupplementaryViewOfKind:kind
                                                                 withReuseIdentifier:@"HELGrowHeader"
                                                                        forIndexPath:indexPath];
        
        
        cell.banner.dataSource = self;
        cell.banner.delegate = self;
        [cell relaodData];
        
        return cell;
    }
    return nil;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section == 0) {
        if (indexPath.row != self.catorgryArray.count) {
            HELCourseListByCatogryVC *vc =[HELCourseListByCatogryVC new];
            HELCatogryModel *model = self.catorgryArray[indexPath.row];
            
            vc.catogryId  = [model.id integerValue];
            vc.catogryName = model.name;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            HELCourseListByCatogryVC *vc =[HELCourseListByCatogryVC new];
          
            
            vc.catogryId  = -1;
            vc.catogryName = @"全部";
            [self.navigationController pushViewController:vc animated:YES];
            
        }
     
        return;
    }
    if (indexPath.section == 1) {
      
        HELCourseListModel *model = self.dataArray[indexPath.row];
        NHCourseDetailVC *vc =[NHCourseDetailVC new];
        vc.courseId = [model.id integerValue];
        [self.navigationController pushViewController:vc animated:YES];
       
    }
    
   
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    HELSearchHistoryVC *vc = [HELSearchHistoryVC new];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    return NO;
}

@end
